package com.hua.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hua.handler.Result;
import com.hua.pojo.Comment;
import com.hua.pojo.Novel;
import com.hua.pojo.Type;
import com.hua.pojo.User;
import com.hua.service.CommentService;
import com.hua.service.NovelService;
import com.hua.service.TypeService;
import com.hua.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/comment")
public class CommentController {

    @Resource
    private CommentService commentService;

    @Resource
    private UserService userService;

    @Resource
    private NovelService novelService;


    //新增一条评论数据
    @PostMapping("/addComment")
    public Result<?> addComment(@RequestBody Comment comment){
        commentService.save(comment);
        return Result.success();
    }

    //根据小说id查询评论数据
    @PostMapping("/selectComment/{novelId}")
    public Result<?> selectComment(@PathVariable String novelId){
//        ArrayList<Comment> commentArrayList = new ArrayList<>();
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getNovelId,novelId);
        List<Comment> list = commentService.list(wrapper);
        list.forEach(item -> {
            String selectUserNickName = userService.getSelectUserNickName(item.getUserId());
            item.setUserId(selectUserNickName);
        });
        return Result.success(list);
    }

    @DeleteMapping
    //Delete为删除，removeByIds为批量删除
    public Result<?> typeDelete(@RequestBody Set<String> ids){
        commentService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping
    //Get为查询
    public Result<?> typeFindPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                  @RequestParam(defaultValue = "10") Integer pageSize,
                                  @RequestParam(defaultValue = "") String search){
        LambdaQueryWrapper<Comment> wrapper= Wrappers.<Comment>lambdaQuery();
        List<Comment> list = commentService.list(wrapper);
        list.forEach(item->{
            String selectUserNickName = userService.getSelectUserNickName(item.getUserId());
            item.setUserId(selectUserNickName);
            String selectNovelName = novelService.getSelectNovelName(item.getNovelId());
            item.setNovelId(selectNovelName);
        });
        if (StrUtil.isNotBlank(search)){
            wrapper.like(Comment::getUserId,search);
        }
        Page<Comment> page = commentService.page(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(list);
    }
}
